import bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author Spring_Hu
 * @date 2021/10/15 8:14
 */
public class TimerExample_update {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> source = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] line = value.split(",");
                        return new WaterSensor(
                                line[0],
                                Long.parseLong(line[1]),
                                Integer.parseInt(line[2]));
                    }
                });


        source.assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forMonotonousTimestamps()
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs()*1000L;
                    }
                }))
                .keyBy(value -> value.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    ValueState<Long> stateTimer;
                    ValueState<Integer> stateVc;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        stateTimer = getRuntimeContext().getState(
                                new ValueStateDescriptor<Long>("stateTimer",
                                        Types.LONG,0L));
                        stateVc = getRuntimeContext().getState(
                                new ValueStateDescriptor<Integer>("Integer",
                                        Types.INT,0));
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                        //watermark
                        //判断初始的时间戳是否为-1

                        //为-1则注册 以当前事件时间开始 一个5s的定时器
                        if(stateTimer.value()==0L){
                            stateTimer.update(ctx.timestamp()+5000L);
                            System.out.println("第一次注册定时器....");
                            ctx.timerService().registerEventTimeTimer(stateTimer.value());
                            //将最大的时间戳赋值给当前的watermark
                        }
                        //不为-1 则获取当前的水位 判断水位是否上涨
                        //1.上涨 则不处理
                        if(value.getVc()<stateVc.value()){

                            //2.不上涨则 删除当前注册的定时器 以当前时间为参照 重新注册

                            ctx.timerService().deleteEventTimeTimer(stateTimer.value());

                            stateTimer.update(ctx.timestamp()+5000L);

                            System.out.println("删除后重新注册定时器.....");
                            ctx.timerService().registerEventTimeTimer(stateTimer.value());

                        }

                        //将上次的vc 保存起来
                        stateVc.update(value.getVc());

                    }

                    //时间定时器到了触发时间会调用此方法
                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        System.out.println("onTimer.....");
                        out.collect("告警：水位在连续5s钟内连续上涨，请注意！");
                        //清空本次的定时器
                        stateTimer.clear();
                    }
                }).print();

        env.execute();

    }


}
